package cn.edu.nuc.onlinestore.network.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer implements Runnable{
	
	@SuppressWarnings("unused")
	private static volatile boolean flag=true;
	private int port;
	private static ServerSocket server;
	private static int num=0;
	private static ExecutorService executorService=Executors.newCachedThreadPool();
	public TCPServer(int port){
		this.port=port;
		try{
			server=new ServerSocket(this.port);
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(!executorService.isShutdown()){
			try{
				Socket client=server.accept();//等待连接
				num++;
				executorService.execute(new ServerThread(client,num));
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	public static void start(int port){//守护线程
		Thread tcpServer=new Thread(new TCPServer(port));
		tcpServer.setDaemon(true);
		tcpServer.start();
	}
	public static void stop(){//结束断开每条链接
		executorService.shutdown();
		flag=false;
		Set<Map.Entry<String,Socket>> entries=ServerThread.getClients().entrySet();
		for(Map.Entry<String, Socket> entry:entries){
			try{
				entry.getValue().close();
			}catch(IOException e){
				e.getStackTrace();
			}
		}
		if(server!=null&&!server.isClosed()){
			try {
				server.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
